package cn.lyjuan.payment.third.base.pay.chl.impl.weixin.util;

import cn.lyjuan.payment.third.base.pay.chl.impl.weixin.bean.TransfersDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.security.*;
import java.security.cert.CertificateException;

@Slf4j
public class HttpRequestHandler {

    // 连接超时时间，默认10秒
    private static final int socketTimeout = 10000;

    // 传输超时时间，默认30秒
    private static final int connectTimeout = 30000;

    // 请求器的配置
    private static RequestConfig requestConfig;

    // HTTP请求器
    private static CloseableHttpClient httpClient;

    /**
     * 加载证书
     *
     * @param path path
     * @throws IOException               IOException
     * @throws KeyStoreException         KeyStoreException
     * @throws UnrecoverableKeyException UnrecoverableKeyException
     * @throws NoSuchAlgorithmException  NoSuchAlgorithmException
     * @throws KeyManagementException    KeyManagementException
     */
    private static void initCert(String path, TransfersDto transfer)
            throws IOException, KeyStoreException, UnrecoverableKeyException,
            NoSuchAlgorithmException, KeyManagementException {
        // 拼接证书的路径
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        // 加载本地的证书进行https加密传输
        try (FileInputStream in = new FileInputStream(path)) {
            keyStore.load(in, transfer.getMchid().toCharArray()); // 加载证书密码，默认为商户ID
        } catch (CertificateException | NoSuchAlgorithmException e) {
            log.error("init wx cert error: [{}]", e.getMessage());
            throw new RuntimeException(e);
        }
        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,
                transfer.getMchid().toCharArray()).build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
                new String[]{"TLSv1"}, null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        // 根据默认超时限制初始化requestConfig
        requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
    }

    /**
     * 通过Https往API post xml数据
     *
     * @param url    API地址
     * @param xmlObj 要提交的XML数据对象
     * @param path   当前目录，用于加载证书
     * @return String
     * @throws IOException               IOException
     * @throws KeyStoreException         KeyStoreException
     * @throws UnrecoverableKeyException UnrecoverableKeyException
     * @throws NoSuchAlgorithmException  NoSuchAlgorithmException
     * @throws KeyManagementException    KeyManagementException
     */
    public static String httpsRequest(String url, String xmlObj, TransfersDto model, String path, Integer systemErrorRetryTimes)
            throws IOException, KeyStoreException, UnrecoverableKeyException,
            NoSuchAlgorithmException, KeyManagementException {
        // 加载证书
        initCert(path, model);
        String result = null;
        HttpPost httpPost = new HttpPost(url);
        // 得指明使用UTF-8编码，否则到API服务器XML的中文不能被成功识别
        StringEntity postEntity = new StringEntity(xmlObj, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.setEntity(postEntity);
        // 设置请求器的配置
        httpPost.setConfig(requestConfig);
        HttpResponse response = null;
        systemErrorRetryTimes = systemErrorRetryTimes == null || systemErrorRetryTimes <= 0 ? 1 : systemErrorRetryTimes;
        if (systemErrorRetryTimes >= 10) {
            log.debug("exec wechat transfer request: retryTime: [{}]", systemErrorRetryTimes);
        }
        try {
            for (int i = 0; i < systemErrorRetryTimes; i++) {
                response = httpClient.execute(httpPost);
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "UTF-8");
                if (!WxUtils.checkWxXmlResSystemError(result)) {
                    break;
                }
            }
            log.debug("result: [{}]", result);
        } catch (ConnectionPoolTimeoutException e) {
            log.error("exec wx api error: connection pool timeout: [{}]", e.getMessage());
        } catch (ConnectTimeoutException e) {
            log.error("exec wx api error: connect timeout: [{}]", e.getMessage());
        } catch (SocketTimeoutException e) {
            log.error("exec wx api error: socket timeout: [{}]", e.getMessage());
        } catch (Exception e) {
            log.error("exec wx api error: [{}]", e.getMessage());
        } finally {
            httpPost.abort();
        }
        return result;
    }
}
